package com.fanshilz.flower2025.apps.admin.sysConfig.controller;

import cn.hutool.core.lang.Assert;
import com.fanshilz.flower2025.apps.admin.sysConfig.req.SysConfigSaveOrUpdateReq;
import com.fanshilz.flower2025.apps.admin.sysConfig.req.SysConfigTableReq;
import com.fanshilz.flower2025.apps.admin.sysConfig.resp.SysConfigTableDetailResp;
import com.fanshilz.flower2025.business.sys.sysConfig.entity.SysConfig;
import com.fanshilz.flower2025.business.sys.sysConfig.service.ISysConfigService;
import com.fanshilz.flower2025.framework.exception.CodeException;
import com.fanshilz.flower2025.framework.resp.Resp;
import com.fanshilz.flower2025.framework.resp.TableResp;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import io.github.linpeilie.Converter;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/admin/config")
@RestController
public class SysConfigController {

    @Resource
    private Converter converter;
    @Resource
    private ISysConfigService sysConfigService;

    @PostMapping("/remove/{configId}")
    public Resp<Void> remove(@PathVariable Long configId) {
        boolean b = sysConfigService.updateById(SysConfig.builder()
                .configId(configId)
                .delFlag(true)
                .build());
        Assert.isTrue(b, CodeException::new);
        return Resp.success();
    }

    @PostMapping("/saveOrUpdate")
    public Resp<Void> saveOrUpdate(@RequestBody @Valid SysConfigSaveOrUpdateReq req) {
        SysConfig sc = converter.convert(req, SysConfig.class);
        boolean b = sysConfigService.saveOrUpdate(sc);
        Assert.isTrue(b, CodeException::new);
        return Resp.success();
    }

    @PostMapping("/table")
    public Resp<TableResp<SysConfigTableDetailResp>> table(@RequestBody @Valid SysConfigTableReq req) {
        Page<SysConfigTableDetailResp> page = sysConfigService.pageAs(Page.of(req.getCurrent(), req.getPageSize(), req.getTotal()),
                QueryWrapper.create(), SysConfigTableDetailResp.class);
        return Resp.success(new TableResp<>(page.getRecords(), page.getTotalRow()));
    }

}
